<template>
  <div class="users">
    <el-row>
      <el-col :span=24>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>首页</el-breadcrumb-item>
          <el-breadcrumb-item>用户管理</el-breadcrumb-item>
          <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <!-- 给组件绑定原生事件的话，需要一个.native的修饰符 -->
        <el-input placeholder="请输入内容" class="search-input" v-model="query" @keydown.native.enter="initList">
          <el-button slot="append" icon="el-icon-search" @click="initList"></el-button>
        </el-input>
        <el-button type="success" plain @click="addDialogFormVisible=true">添加用户</el-button>
      </el-col>
    </el-row>
    <el-table :data="userList" v-loading="loading" style="width:100%" class="margin-20">
      <el-table-column type="index">
      </el-table-column>
      <el-table-column prop="username" label="姓名" width="180">
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="180">
      </el-table-column>
      <el-table-column prop="mobile" label="电话" width="180">
      </el-table-column>
      <el-table-column prop="mobile" label="用户状态" width="180">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state" @change="changeState(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button plain size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(scope.row)"></el-button>
          <el-button plain size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)"></el-button>
          <el-button plain size="mini" type="warning" icon="el-icon-check" @click="handleRole(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pagenum" :page-sizes="[5, 10, 20, 30]" :page-size="pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!-- 添加用户弹窗 -->
    <el-dialog title="添加用户" :visible.sync="addDialogFormVisible">
      <el-form :model="addForm" :rules="rules" label-width="80px" ref="addUserForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
           <el-input v-model="addForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
           <el-input v-model="addForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
           <el-input v-model="addForm.mobile" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddUser('addUserForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑用户弹窗 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogFormVisible">
      <el-form :model="editForm" label-width="80px" :rules="rules" ref="editUserForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" auto-complete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditUser('editUserForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色弹窗 -->
    <el-dialog title="角色分配" :visible.sync="ruleDialogFormVisible">
      <el-form :model="ruleForm" label-width="120px" :rules="rules" ref="ruleUserForm">
        <el-form-item label="用户名" prop="username">
          <el-tag type="info">{{ruleForm.username}}</el-tag>
        </el-form-item>
        <el-form-item label="请选择当前角色">
          <el-select v-model="ruleForm.role_id" placeholder="请选择">
            <el-option
              v-for="(item,index) in roleOptions"
              :key="index"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="ruleDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="grantRoleSubmit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUsers, addUser, getUserById, editUser, deleteUser, changeUserState, getRoleList, grantUserRole } from '@/api/api.js'
export default {
  data () {
    return {
      query: '',
      pagenum: 1,
      pagesize: 5,
      total: 0,
      userList: [],
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editForm: {
        username: '',
        email: '',
        mobile: '',
        id: 0
      },
      ruleForm: {},
      roleOptions: [],
      loading: false,
      addDialogFormVisible: false,
      editDialogFormVisible: false,
      ruleDialogFormVisible: false,
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur,change' }
        ],
        mobile: [
          { required: true, message: '电话不能为空' }
        ]
      }
    }
  },
  created () {
    this.initList()
  },
  methods: {
    // 分页
    handleSizeChange (val) {
      this.pagesize = val
      this.initList()
    },
    // 分页
    handleCurrentChange (val) {
      this.pagenum = val
      this.initList()
    },
    // 显示编辑用户弹窗并获取用户
    handleEdit (row) {
      this.editDialogFormVisible = true
      getUserById(row.id).then(res => {
        if (res.meta.status === 200) {
          this.editForm.username = res.data.username
          this.editForm.email = res.data.email
          this.editForm.mobile = res.data.mobile
          this.editForm.id = res.data.id
        }
      })
    },
    // 编辑用户提交
    submitEditUser (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          editUser(this.editForm).then(res => {
            if (res.meta.status === 200) {
              this.initList()
              this.$message({
                type: 'success',
                message: res.meta.msg
              })
            } else {
              this.$message({
                type: 'error',
                message: res.meta.msg
              })
            }
          })
          this.editDialogFormVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 删除用户
    handleDelete (row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser(row.id).then(res => {
          if (res.meta.status === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.initList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    // 显示角色分配框
    handleRole (row) {
      this.ruleDialogFormVisible = true
      this.ruleForm = row
      getRoleList().then(res => {
        if (res.meta.status === 200) {
          this.roleOptions = res.data
        }
      })
    },
    // 分配角色
    grantRoleSubmit () {
      if (this.ruleForm.role_id) {
        grantUserRole({id: this.ruleForm.id, rid: this.ruleForm.role_id}).then(res => {
          if (res.meta.status === 200) {
            this.$message({
              type: 'success',
              message: '设置角色成功'
            })
            this.ruleDialogFormVisible = false
          } else {
            this.$message({
              type: 'error',
              message: res.meta.msg
            })
          }
        })
      } else {
        this.$message({
          type: 'warning',
          message: '角色不能为空，请选择！'
        })
      }
    },
    // 更改用户状态
    changeState (obj) {
      changeUserState({uId: obj.id, type: obj.mg_state}).then(res => {
        if (res.meta.status === 200) {
          this.$message({
            type: 'success',
            message: '修改用户状态成功'
          })
        } else {
          this.$message({
            type: 'warning',
            message: res.meta.msg
          })
        }
      })
    },
    // 渲染表格
    initList () {
      this.loading = true
      getUsers({
        params: {
          query: this.query,
          pagenum: this.pagenum,
          pagesize: this.pagesize
        }
      }).then(res => {
        if (res.meta.status === 200) {
          this.userList = res.data.users
          this.total = res.data.total
          this.pagenum = res.data.pagenum
          this.loading = false
        }
      })
    },
    // 增加用户
    submitAddUser (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          addUser(this.addForm).then(res => {
            if (res.meta.status === 201) {
              this.initList()
              this.$message({
                type: 'success',
                message: res.meta.msg
              })
            } else {
              this.$message({
                type: 'error',
                message: res.meta.msg
              })
            }
          })
          this.addDialogFormVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.users {
  .margin-20 {
    margin: 20px 0;
  }
  .search-input {
    width: 300px;
  }
  .page {
    padding: 5px 0;
    background-color: #d3dce6;
  }
}
</style>
